package com.alfred.springboot.cors.config;

import cn.hutool.core.collection.CollUtil;
import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @author: alfred
 * @date: 2021/7/19
 * @description: 跨域配置类
 */
@Data
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    private List<String> allowOriginUrls = Arrays.asList(new String[]{"https://www.cnblogs.com"});

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        if(CollUtil.isNotEmpty(allowOriginUrls)) {
            // 允许发起跨域请求的域名（自行设置）
            corsConfiguration.setAllowedOrigins(allowOriginUrls);
        }
        // 允许任何域名使用
        // corsConfiguration.addAllowedOrigin("*");
        // 允许任何头
        corsConfiguration.addAllowedHeader("*");
        // 允许任何方法（post、get等）
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

}
